﻿using FC.ERP.TMom.Api.AppHandlers.Commands.EssentialDatas.FactoryManages.Workstations;
using FC.ERP.TMom.Api.DTOs;
using FC.ERP.TMom.Domain;
using FC.ERP.TMom.ErrorCode;
using FC.ERP.TMom.Infrastructure.Interfaces;
using MediatR;

namespace FC.ERP.TMom.Api.AppHandlers.CommandHandlers.EssentialDatas.FactoryManages.Workstations
{
    public class WorkstationQuertyCommandHandler : IRequestHandler<WorkstationQuertyCommand, APIResult<APIPaging<WorkstationDTO>>>
    {
        private readonly IBaseRepository<Workstation> workstationrepository;
        private readonly IBaseRepository<Line> linerepository;
        private readonly IBaseRepository<ProcessOperation> processrepository;
        public WorkstationQuertyCommandHandler(IBaseRepository<Workstation> workstationrepository, IBaseRepository<Line> linerepository, IBaseRepository<ProcessOperation> processrepository)
        {
            this.workstationrepository = workstationrepository;
            this.linerepository = linerepository;
            this.processrepository = processrepository;
        }
        public Task<APIResult<APIPaging<WorkstationDTO>>> Handle(WorkstationQuertyCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<WorkstationDTO>> result=new APIResult<APIPaging<WorkstationDTO>>(){};
            result.Code=ResultCode.查询成功;
            result.Message=ResultCode.查询成功.ToString();
            var list = from a in workstationrepository.GetAll()
                       join b in linerepository.GetAll() on a.LineId equals b.LineId
                       join c in processrepository.GetAll() on a.ProcessOperationId equals c.ProcessOperationId
                       where !a.IsDeleted
                       select new WorkstationDTO
                       {
                           WorkstationId = a.WorkstationId,
                           WorkstationCode = a.WorkstationCode,
                           WorkstationName = a.WorkstationName,
                           Description = a.Description,
                           CreateId = a.CreateId,
                           CreateTime = a.CreateTime,
                           UpdateTime = a.UpdateTime,
                           LineId = b.LineId,
                           LineName = b.LineName,
                           ProcessOperationId=c.ProcessOperationId,
                           ProcessOperationName = c.ProcessOperationName,

                       };
            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<WorkstationDTO> entity = new APIPaging<WorkstationDTO>();
            entity.TotalCount = totalCount;
            entity.TotalPage = totalPage;
            entity.List = list.ToList();
            result.Data = entity;
            return Task.FromResult(result);
        }
    }
}
